#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@File    :   items.py
@Time    :   2023/04/19 21:03:40
@Author  :   Rico Chen 
@Mail    :   55059@qq.com
@Version :   1.0
@Desc    :   投资网取出BAID, 然后给tab_ba_detail.py去查询详情
"""
import os
import sys
from pathlib import Path
import os
import sys
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent
sys.path.insert(0, os.path.join(BASE_DIR))

from peewee import *
from datetime import datetime
from typing import Optional
import json
from apps.utils.common import *
from models.db_pool import *

class LastSpider(BaseModel):
    flag_id      = CharField(10,primary_key=True,verbose_name="项目标识")
    last_record_Id = CharField(50,verbose_name="最后一条项目ID",)
    last_spider_date = DateTimeField(verbose_name="最后爬出日期")
    
    class Meta:
        db_table = "tab_last_spy"
    
    @staticmethod
    @db.connection_context()
    def update_last_date(flag_id="beian",baid ="没记录", finishDate = datetime.now()):
        p = LastSpider.get(LastSpider.flag_id == flag_id)
        p.last_record_Id = baid
        p.last_spider_date = finishDate
        p.save()

    @staticmethod
    @db.connection_context()
    def get_last_date(flag="beian"):
        '''
        返回最新的一条插入记录备案ID
        '''
        try:
            last_rec = LastSpider.get(flag_id="beian")
            rst_date = last_rec.last_spider_date.strftime('%Y-%m-%d')
            rst_baid = last_rec.last_record_Id
        except:
            rst_date="2000-01-01"
            rst_baid="没记录"
        return rst_date, rst_baid
    
class BeiAn(BaseModel):
    baId = CharField(
        50,
        verbose_name="项目ID",
        primary_key=True,
    )
    projectCode = CharField(100, verbose_name="备案项目编号")
    totalMoney = FloatField(verbose_name="金额")
    fullName = CharField(100, verbose_name="项目业主")
    finishDate = CharField(50, verbose_name="备案通过日期")
    stateFlagName = CharField(50, verbose_name="状态")
    projectName = CharField(200, verbose_name="项目名称")
    createDate = DateTimeField(default=datetime.now, verbose_name="创建日期")
    updatedDate = DateTimeField(default=datetime.now, verbose_name="更新日期")
    isGet = IntegerField(default=0, verbose_name="已取")

    class Meta:
        db_table = "tab_beian"

    # 计算属性元
    @property
    def money(self):
        return "%d" + self.totalMoney * 1000
    
    @staticmethod
    @db.connection_context()
    def update_last_spider_date(baid:str="没记录",finishDate:str="2000-01-01"):
        LastSpider.update_last_date('beian',baid,datetime.strptime(finishDate,'%Y-%m-%d'))
    
    @staticmethod
    def last_spider_date():
        '''
        返回最新的一条插入记录备案ID
        '''
        return LastSpider.get_last_date("beian")

    @staticmethod
    @db.connection_context()
    def empty_get():
        '''
        删除已取记录。
        '''
        BeiAn.delete().where(BeiAn.isGet != 0).execute()
    
    @staticmethod
    #@db.atomic()
    @db.connection_context()
    def insert__from_list(data_list: list):
        """
        数据批量插入数据库
        data_list = [{"baId": "1"...},{},]
        """
        BeiAn.insert_many(
            data_list,
            fields=[
                "baId",
                "projectCode",
                "totalMoney",
                "fullName",
                "finishDate",
                "stateFlagName",
                "projectName",
            ],
        ).on_conflict_ignore(ignore=True).execute()


if __name__ == "__main__":
    data_list = [
        {
            "baId": "1649223131300102146",
            "projectCode": "2304-441900-04-01-135254",
            "totalMoney": 50,
            "fullName": "东莞市长安镇经济发展局",
            "finishDate": "2023-04-21",
            "stateFlagName": "办结（通过）",
            "projectName": "东莞市长安镇振安东路155号101.26kWp分布式光伏发电项目",
        },
        {
            "baId": "1649223156969242625",
            "projectCode": "2304-441900-04-01-386559",
            "totalMoney": 20,
            "fullName": "东莞市长安镇经济发展局",
            "finishDate": "2023-04-21",
            "stateFlagName": "办结（通过）",
            "projectName": "东莞市长安镇霄边上洋路17号35.69kWp分布式光伏发电项目",
        },
    ]
    with db.connection_context():
        db.connect(reuse_if_open=True)
        #LastSpider.create_table()
        # p = LastSpider()
        # p.flag_id = "beian"
        # p.last_record_Id="没有记录"
        # p.last_spider_date="2000-1-1"
        # p.save(force_insert=True)

        # if not BeiAn.table_exists():
        #     print("表不存在,创建中", BeiAn.table_exists)
        #     db.create_tables([BeiAn])

        # BeiAn.insert__from_list(data_list)
        # print(db.is_closed())
        # t :str = BeiAn.get_last()
        # print(t)
        LastSpider.get_last_date("beian")
        LastSpider.update_last_date("beian")